<?php
/**
 *MessageSend
 *@author  Jiangzhendong
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;

class MessagesendController extends BaseController {
    // get CompanyAccount 
    public function GetCompanyAccount(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $callfun = M('qy')->field('qy_code,qy_name')->where(array('is_deleted'=>array('neq',1)))->select();
        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $callfun;
        }
        e_json($res);
    }

    // get qy_app
    public function GetQyApp(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $qyaccount = I('post.qyaccount','','trim');
        $callfun = M('qy')->field('qy_code,qy_name')->where(array('is_deleted'=>array('neq',1)))->select();
        $callfun = M('qy_app')  ->alias('a')
                                ->field('a.qy_app_id,a.qy_app_name,c.qy_name')
                                ->join('LEFT JOIN qy_app_admin as b ON b.qy_app_id = a.qy_app_id')
                                ->join('LEFT JOIN qy as c ON c.qy_code = a.qy_code')
                                ->where(array('a.qy_code'=>$qyaccount,'b.user_id'=>$this->m_user['user_id']))
                                ->select();
        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $callfun;
            $res['sql'] = M('qy_app')->getlastsql();
        }
        e_json($res);
    }

    // get all object
    public function GetAllObj(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $arr = array();
        $att = array();
        $arrcombine = array();
        $qyapp = I('post.qyapp','','trim');
        $callfun = M('qy_app')  ->alias('a')
                                ->field('c.package_code as val,c.name,d.name as product_name')
                                ->join('LEFT JOIN qy_app_package as b ON a.qy_app_id = b.qy_app_id')
                                ->join('LEFT JOIN product_package as c ON c.package_code = b.package_code')
                                ->join('LEFT JOIN product as d ON d.product_id  = c.product_id ')
                                ->where(array('a.qy_app_id'=>$qyapp))
                                ->select(); 
        
        foreach($callfun as $k => $v){
            $callfun[$k]['val'] = 'pc_'.$v['val'];
            $callfun[$k]['name'] = $v['name'].'('.$v['product_name'].')';
            unset($v['product_name']);
        }

        $callfunsubscriber = M('qy_app')->alias('m')
                                        ->distinct(true)
                                        ->field('w.qy_subscriber_name as name,w.qy_subscriber_userid as val')
                                        ->join('JOIN qy_app_package as n ON n.qy_app_id = m.qy_app_id')
                                        ->join('JOIN product_package as z ON z.package_code = n.package_code')
                                        ->join('JOIN qy_subscriber as w ON FIND_IN_SET(z.qy_deparment_id,w.qy_subscriber_department)>0')
                                        ->where(array('m.qy_app_id'=>$qyapp))
                                        ->select();
        foreach($callfunsubscriber as $key => $val){
            $callfunsubscriber[$key]['val'] = 'su_'.$val['val'];
        }
        foreach($callfunsubscriber as $key => $val){
            if(!in_array($val['val'],$arr)){
                $arr[] = $val['val'];
                $att[] = $callfunsubscriber[$key];
            }
        }

        $arrcombine = array_merge($callfun,$att);

        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $arrcombine;
            $res['subscriber'] = $callfunsubscriber;
            $res['test'] = $att;
            $res['callfun'] = $callfun;
        }
        e_json($res);
    }

    // get subscriber
    public function GetSubScriber(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
        $val = I('post.obj','','trim');
        $val = substr($val,3);
        $callfun = M('product_package') ->alias('a')
                                        ->field('b.qy_subscriber_userid as val,b.qy_subscriber_name as name')
                                        ->join('LEFT JOIN qy_subscriber as b ON FIND_IN_SET(a.qy_deparment_id,b.qy_subscriber_department)>0')
                                        ->where(array('a.package_code'=>$val))
                                        ->select();
        foreach($callfun as $key => $val){
            $callfun[$key]['val'] = 'su_'.$val['val'];
        }
        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $callfun;
        }
        e_json($res);
    }

    // add multiple files
	public function uploadmultiplefiles(){
        if (IS_GET) {
            //
        }
        else{
            $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'Error');
            $fname = I('post.name','multiplefiles', 'trim');
            $newName = I('post.newname','','trim');
            $from = I('post.from','', 'trim');
            $Mdo = new \Common\ORG\AttUpload();
            if ( $_FILES && isset( $_FILES[$fname] ) ){
                $fupload = $_FILES[$fname];
                $is_multi = is_array($fupload['error'])  ? true : false;
                $res['f'] = $is_multi;
                if ( (!$is_multi&&$fupload['error'] != 0) || ($is_multi&&count($fupload['error'])==0)  ||
                         ($is_multi && $fupload['error'][0]!=0 )){
                    $res['msg'] = "上传文件发生错误";
                }
                else {
                    if ($is_multi) {  // 二维数组批量上传文件
                        $res = array('rcode'=>0,'data'=>array(),'msg'=>'Error');
                        $allFileSize = count($fupload['name']);
                        $countUploaded = 0;
                        for ($i=0;  $i<$allFileSize; $i++) {
                            $ret = $Mdo->upload( $fupload['name'][$i], $fupload['tmp_name'][$i], $newName);
                            if ($ret&&$ret['rcode']){
                                $countUploaded++;
                                $res['view_path'][] = $ret['data']['view_path'];
								$res['source_name'][]= $ret['data']['source_name'];
                            } 
                            
                        }
                        if ($countUploaded) {
                            $res['rcode'] = 1;
                            $res['msg'] = "OK";
                        }
                        else 
                            $res['msg'] = "批量上传文件失败";
                    }
                    else {
                        $ret = $Mdo->upload( $fupload['name'], $fupload['tmp_name'], $newName);
						$res['view_path'] = $ret['data']['view_path'];
						$res['source_name'] = $ret['data']['source_name'];
                        // $res['name'] = $ret['data']['name'];
                    }
                }
            }
            else
                $res['msg'] = "获取上传文件失败";
            e_json( $res );
        }		
	}

    // message send list
    public function Index(){
        $substr = '';
        $res = array('rcode'=>0,'data'=>'','msg'=>'');
        $msgtype = I('post.msgtype','','trim');
        $searchobj = I('post.searchobj','','trim');
        $qyaccount = I('post.qy_code','','trim');
        $qy_app_id = I('post.qy_app_id','','trim');
        $radio = I('post.radio','','trim');
        $chk = I('post.chk',0,'intval');
        $index = I('post.k',false,'intval');
        foreach($searchobj as $key => $val){
            $substr = substr($val,0,3);
            if($substr == 'pc_'){
                $pcstr = $pcstr.substr($val,3).'|';
            }else{
                $sustr = $sustr.substr($val,3).'|';
                $sustr = rtrim($sustr);
            }
        }
        $pcstr = substr($pcstr, 0, -1);
        $sustr = substr($sustr, 0, -1);
        if($sustr){
            $touser = $sustr;
        }
        if($pcstr){
            $toparty = $pcstr;
        }
        // if($totag){
        //     $totag = '2';
        // }
        if($radio['regularradiochk']){
            $data['send_type'] = 20;
        }
        if($radio['tempradiochk']){
            $data['send_type'] = 10;
        }



        if($index == 1){
            $arr = array('articles'=>array());
            $mpnews = I('post.mpnews');
            $agentid = 1;
            if($mpnews){
                foreach($mpnews['articles'] as $key => $val){
                    $arr['articles'][$key]['title'] = $val['title'];
                    $arr['articles'][$key]['thumb_media_id'] = $val['thumb_media_id'];
                    $arr['articles'][$key]['author'] = $val['author'];
                    $arr['articles'][$key]['content_source_url'] = '';
                    $arr['articles'][$key]['content'] = $val['content'];
                    $arr['articles'][$key]['digest'] = '';
                    $arr['articles'][$key]['show_cover_pic'] = $val['is_checked'];
                }
            }
            $MQy =  new \Common\ORG\Qy('zytg');
            $returnDate = $MQy->uploadmpnewsMessage($touser,$toparty,$totag,$msgtype,$agentid,$arr,$chk);
            if($returnDate){
                if($returnDate['data']['invalidparty']){
                    $data['touser'] = $returnDate['data']['invalidparty'];
                }
                if($returnDate['data']['invaliduser']){
                    $data['toparty'] = $returnDate['data']['invaliduser'];
                }
                if($returnDate['data']['totag']){
                    $data['totag'] = $returnDate['data']['totag'];
                }
                $data['agentid'] = $agentid;
                $data['qy_code'] = $qyaccount;
                $data['qy_app_id'] = $qy_app_id;
                $data['message_content'] = serialize($arr);
                $callfun = M('qy_message')->add($data);
                if($callfun){
                    $res['rcode'] = 1;
                    $res['data'] = $arr;
                    $res['returnDate'] = $returnDate;
                    $res['chk'] = $chk;
                    $res['radio'] = $radio;
                }
            }
        }else if($index == 2){
            $media = I('post.file','','trim');
            $agentid = 1;
            $MQy =  new \Common\ORG\Qy('zytg');
            $returnDate = $MQy->uploadfilemsgMessage($touser,$toparty,$totag,$msgtype,$agentid,$media,$chk);    
            if($returnDate){
                if($returnDate['data']['invalidparty']){
                    $data['touser'] = $returnDate['data']['invalidparty'];
                }
                if($returnDate['data']['invaliduser']){
                    $data['toparty'] = $returnDate['data']['invaliduser'];
                }
                if($returnDate['data']['totag']){
                    $data['totag'] = $returnDate['data']['totag'];
                }
                $data['agentid'] = $agentid;
                $data['qy_code'] = $qyaccount;
                $data['qy_app_id'] = $qy_app_id;  
                $data['message_content'] = serialize($media);    
                $callfun = M('qy_message')->add($data);
                if($callfun){
                    $res['rcode'] = 1;
                    $res['data'] = $arr;
                    $res['returnDate'] = $returnDate;
                }                        
            }        
        }else if($index == 5){
            $media = I('post.img','','trim');
            $agentid = 1;
            $MQy =  new \Common\ORG\Qy('zytg');
            $returnDate = $MQy->uploadfilemsgMessage($touser,$toparty,$totag,$msgtype,$agentid,$media,$chk); 
            if($returnDate){
                if($returnDate['data']['invalidparty']){
                    $data['touser'] = $returnDate['data']['invalidparty'];
                }
                if($returnDate['data']['invaliduser']){
                    $data['toparty'] = $returnDate['data']['invaliduser'];
                }
                if($returnDate['data']['totag']){
                    $data['totag'] = $returnDate['data']['totag'];
                }
                $data['agentid'] = $agentid;
                $data['qy_code'] = $qyaccount;
                $data['qy_app_id'] = $qy_app_id;  
                $data['message_content'] = serialize($media);    
                $callfun = M('qy_message')->add($data);
                if($callfun){
                    $res['rcode'] = 1;
                    $res['data'] = $arr;
                    $res['returnDate'] = $returnDate;
                }
            }   
        }else if($index == 4){
            $text = I('post.text','','trim');
            $agentid = 1;
            $MQy =  new \Common\ORG\Qy('zytg');
            $returnDate = $MQy->uploadtextMessage($touser,$toparty,$totag,$msgtype,$agentid,$text,$chk);
            if($returnDate){
                if($returnDate['data']['invalidparty']){
                    $data['touser'] = $returnDate['data']['invalidparty'];
                }
                if($returnDate['data']['invaliduser']){
                    $data['toparty'] = $returnDate['data']['invaliduser'];
                }
                if($returnDate['data']['totag']){
                    $data['totag'] = $returnDate['data']['totag'];
                }
                $data['agentid'] = $agentid;
                $data['qy_code'] = $qyaccount;
                $data['qy_app_id'] = $qy_app_id;  
                $data['message_content'] = serialize($text);    
                $callfun = M('qy_message')->add($data);
                if($callfun){
                    $res['rcode'] = 1;
                    $res['data'] = $text;
                    $res['returnDate'] = $returnDate;
                }
            } 
        }else if($index == 3){
            $arr = array('articles'=>array());
            $mpnews = I('post.mpnews');
            $agentid = 1;
            if($mpnews){
                foreach($mpnews['articles'] as $key => $val){
                    $arr['articles'][$key]['title'] = $val['title'];
                    $arr['articles'][$key]['thumb_media_id'] = $val['thumb_media_id'];
                    // $arr['articles'][$key]['author'] = '';
                    // $arr['articles'][$key]['content_source_url'] = '';
                    $arr['articles'][$key]['content'] = $val['content'];
                    // $arr['articles'][$key]['digest'] = '';
                    $arr['articles'][$key]['show_cover_pic'] = $val['is_checked'];
                }
            }
            $MQy =  new \Common\ORG\Qy('zytg');
            $returnDate = $MQy->uploadmpnewsMessage($touser,$toparty,$totag,$msgtype,$agentid,$arr,$chk);
            if($returnDate){
                if($returnDate['data']['invalidparty']){
                    $data['touser'] = $returnDate['data']['invalidparty'];
                }
                if($returnDate['data']['invaliduser']){
                    $data['toparty'] = $returnDate['data']['invaliduser'];
                }
                if($returnDate['data']['totag']){
                    $data['totag'] = $returnDate['data']['totag'];
                }
                $data['agentid'] = $agentid;
                $data['qy_code'] = $qyaccount;
                $data['qy_app_id'] = $qy_app_id;
                $data['message_content'] = serialize($arr);
                $callfun = M('qy_message')->add($data);
                if($callfun){
                    $res['rcode'] = 1;
                    $res['data'] = $arr;
                    $res['returnDate'] = $returnDate;
                }
            }
        }
        e_json($res); 
    }

    // wechat file upload
    public function fileupload(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'Error');      
        $path = I('post.path');
        $msgtype = I('post.type');
        $comfileparam = __ROOT__.$path;
        $MQy =  new \Common\ORG\Qy('zytg');
        $returnDate = $MQy->uploadfileMessage($msgtype,$comfileparam);
        e_json($returnDate);
    }

    // knowledge property
    public function knowledgelist(){
        $wheres = array();
        $wheres['_string'] = '1=1';
        $state = I('get.state', -1,'intval');
        $psize = I('get.psize', $this->m_psize,'intval');
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');

        $knowledge_spot_id = I('get.knowledge_spot_id',false,'intval');
        $msgtype = I('get.radioId','','intval');
        if($knowledge_spot_id){
            $wheres['kl.knowledge_spot_id'] = $knowledge_spot_id;
            $wheres['kl.msg_type'] = $msgtype;
            $wheres['kl.is_delete'] = array('neq', 1);
            if( !$psize )
                $psize = $this->m_psize;
            else if( $psize > 20 )
                $psize = $this->m_psize;				
            $cnt = D('Admin/Knowledge')
                                        ->alias("kl")
                                        ->field('kl.*,b.sector_name')
                                        ->join('LEFT JOIN  user as a ON a.user_id = kl.author_id')
                                        ->join('LEFT JOIN  sector as b ON b.sector_id = a.sector_id')
                                        ->where($wheres)
                                        ->count();
            $Page = new \Common\ORG\Page( $cnt, $psize );		
            $dlist = D('Admin/Knowledge')
                                        ->alias("kl")
                                        ->field('kl.*,b.sector_name')
                                        ->join('LEFT JOIN  user as a ON a.user_id = kl.author_id')
                                        ->join('LEFT JOIN  sector as b ON b.sector_id = a.sector_id')
                                        ->where($wheres)
                                        ->order('kl.create_time desc')
                                        ->limit($Page->firstRow.','.$Page->listRows )
                                        ->select();

            if($dlist){
                foreach($dlist as $key => $value){
                    if($value['msg_type'] == 2){
                        $knowledgefile= M('knowledge_file')->where(array('knowledge_id'=>$value['knowledge_id']))->find();
                        $dlist[$key]['name'] = $knowledgefile['file_original_name'];
                        $dlist[$key]['id'] = $knowledgefile['knowledge_file_id'];
                    }else{
                        $dlist[$key]['name'] = 0;
                        $dlist[$key]['id'] = 0;
                    }
                }	
            }

            if($dlist){				
                $res['rcode'] = 1;
                $res['is_picture'] = 2;
                $res['data'] = $dlist;
                $res['pall'] =  $Page->getTotalPages();
                $res['p'] = $Page->nowPage;
                $res['psize'] = $psize;
                $res['msg_type'] = $msgtype;
            }else{
                // 
                $res['is_picture'] = 2;
                $res['msg'] = '您的查询结果有误';
            }			
        }else{
            $res['data'] = '查询结果为空';
            $res['is_picture'] = 1;
        }
        e_json($res);      
    }

	// get knowledgeright data
	public function GetKnowledgeData(){
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$arr = $sec = $user = array();
        $msgtype = I('post.msg_type','','intval');
		if($this->m_is_admin){
			$callfun = M('knowledge_spot')->where(array('is_delete'=>array('neq',1)))->order('code asc')->select();
		}else{
			$data = M('sector')->select();
			$callfunsec = GetParentSector($data,$this->m_user['sector_id']);
			$callfunall = M('knowledge_spot_sector_right')->distinct(true)->field('knowledge_spot_id')->where(array('sector_id'=>array('IN',$callfunsec)))->select();
			if($callfunall){
				foreach($callfunall  as $key => $val){
					$sec[] = $val['knowledge_spot_id'];
				}				
			}
			$callfunuser = M('knowledge_spot_user_right')->distinct(true)->field('knowledge_spot_id')->where(array('user_id'=>$this->m_user['user_id']))->select();
			if($callfunuser){
				foreach($callfunuser as $kuser =>$vuser){
					$user[] = $vuser['knowledge_spot_id'];
				}
			}

			if($sec || $user){              
				$callfun = M('knowledge_spot')-> where(array('knowledge_spot_id'=>array('IN',array_unique(array_merge($sec,$user))),'is_delete'=>array('neq',1)))->order('code asc')->select();
			}
		}
        if($callfun){
            foreach($callfun as $key => $val){
                if(strlen($val['code']) == 2){
					$callfun[$key]['disabled'] = 1;
                }else{
					$callfun[$key]['disabled'] = 2;
                }
            }
            if($callfun){
                $res['rcode'] = 1;
                $res['data'] = $callfun;
            }            
        } 
        e_json($res);	
	}

    // get knowledge msg
    public function GetKnowledgeMsg(){
        $res = array('rcode'=>0,'data'=>'','msg'=>'');
        $knowledgeId = I('post.knowledgeId',false,'intval');
        $msgtype = I('post.msg_type',false,'intval');
        if($msgtype == 1){
            if($knowledgeId){
                $callfun  = M('knowledge')->where(array('knowledge_id'=>$knowledgeId))->find();
            }
        }else if($msgtype == 2){
            if($knowledgeId){
                $callfun  = M('knowledge')->alias('a')
                                          ->field('b.knowledge_file_name,b.file_original_name')
                                          ->join('LEFT JOIN knowledge_file as b ON a.knowledge_id = b.knowledge_id')
                                          ->where(array('a.knowledge_id'=>$knowledgeId))
                                          ->find();
            }
        }else{
            if($knowledgeId){
                $callfun  = M('knowledge')->where(array('knowledge_id'=>$knowledgeId))->find();
            }
        }
        if($callfun){
            $res['rcode'] = 1;
            $res['data'] = $callfun;
        }
        e_json($res);
    }
}
?>